<template>
	<div class="slider-check-box">
		<div class="slider-check" :class="rangeStatus ? 'success' : ''">
			<i @mousedown="rangeMove" :class="rangeStatus"></i>
			{{ rangeStatus ? successText : startText }}
		</div>
	</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { Message } from '@arco-design/web-vue';

interface ModelEmits {
	(e: 'successFunc'): void;
	(e: 'errorFunc'): void;
}

const emit = defineEmits<ModelEmits>();

const successText = '验证成功';
const startText = '请拖住滑块，拖动到最右边';

const disX = ref(0);
const rangeStatus = ref(false);

//滑块移动
const rangeMove = (e: any) => {
	let ele = e.target;
	let startX = e.clientX;
	let eleWidth = ele.offsetWidth;
	let parentWidth = ele.parentElement.offsetWidth;
	let MaxX = parentWidth - eleWidth;

	if (rangeStatus.value) {
		//不运行
		return false;
	}

	document.onmousemove = (e) => {
		let endX = e.clientX;
		disX.value = endX - startX;
		if (disX.value <= 0) {
			disX.value = 0;
		}
		if (disX.value >= MaxX - eleWidth) {
			//减去滑块的宽度,体验效果更好
			disX.value = MaxX;
		}
		ele.style.transition = '.1s all';
		ele.style.transform = 'translateX(' + disX.value + 'px)';
		e.preventDefault();
	};

	document.onmouseup = () => {
		if (disX.value !== MaxX) {
			ele.style.transition = '.5s all';
			ele.style.transform = 'translateX(0)';
			//执行失败的函数
			emit('errorFunc');
		} else {
			rangeStatus.value = true;
			//执行成功的函数
			emit('successFunc');
		}
		document.onmousemove = null;
		document.onmouseup = null;
	};
};
</script>

<style scoped lang="scss">
$blue: #1978fa;
@mixin jc-flex {
	display: flex;
	justify-content: center;
	align-items: center;
}
.slider-check-box {
	width: 100%;
	.slider-check {
		background-color: #e9e9e9;
		position: relative;
		transition: 1s all;
		user-select: none;
		color: #585858;
		@include jc-flex;
		height: 36px;
		&.success {
			background-color: $blue;
			color: #fff;
			i {
				color: $blue;
			}
		}
		i {
			position: absolute;
			left: 0;
			width: 50px;
			height: 100%;
			color: $blue;
			background-color: white;
			border: 1px solid #dbdbdb;
			cursor: pointer;
			font-size: 24px;
			@include jc-flex;
		}
	}
}
</style>
